﻿using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AutoMapper;
using K9Nano.Configuration;
using K9Nano.Dependency;
using K9Nano.Domain;
using K9Nano.Runtime;
using Microsoft.Extensions.Logging;

namespace K9Nano.Application.Settings
{
    public class SettingsAppService : K9ApplicationService, IScopedDependency, ISettingsAppService
    {
        protected readonly ISettingStore SettingStore;
        protected readonly ISettingDefinitionManager SettingDefinitionManager;

        public SettingsAppService(IUnitOfWork uow, IMapper mapper, ISessionContext sessionContext, ILoggerFactory loggerFactory, ISettingStore settingStore, ISettingDefinitionManager settingDefinitionManager) : base(uow, mapper, sessionContext, loggerFactory)
        {
            SettingStore = settingStore;
            SettingDefinitionManager = settingDefinitionManager;
        }

        public virtual async Task<AppSettingsDto> GetAppSettingsAsync(CancellationToken cancellation)
        {
            var settings = await SettingStore.GetAllListAsync(SessionContext.TenantId, SessionContext.UserId, cancellation);
            var defines = SettingDefinitionManager.GetAllSettingDefinitions()
                .Where(x => x.IsVisibleToClients);

            var clientSettings = 
                (
                    from d in defines
                    join s in settings on d.Name equals s.Name into g
                    from result in g.DefaultIfEmpty()
                    select new KeyValuePair<string,string>(d.Name, result == null ? d.DefaultValue : result.Value)
                )
                .ToList();

            var dto = new AppSettingsDto(clientSettings);
            return dto;
        }
    }
}